<template>
  <div class="add-field-module">
    <el-dialog
      v-loading="loading"
      :visible.sync="dialogVisible"
      :before-close="handleClose"
      :show-close="false"
      :append-to-body="true"
      class="add-field-dialog medium-common-dialog-size"
      width="55%">
      <div class="file-list">
        <div class="import-btn-container">
          <ImportBtn
            :hide-confirm="true"
            :radio-list="radioList"
            :import-api="importApi"
            :is-need-base-filed="isNeedBaseFiled"
            btn-text="导入数据"
            style="margin-bottom: 20px;margin-right: 10px;"
            @onGetList="onSucess"/>
        </div>
        <div class="table-name-container">
          <el-tag
            v-for="(tag, index) in fileName"
            :key="index"
            class="tag"
            closable
            @close="deleteTable(tag)">
            <el-tooltip placement="top" effect="dark">
              <div slot="content" style="max-width: 200px;">{{ tag.label }}</div>
              <span class="text-overflow">{{ tag.label }}</span>
            </el-tooltip>
          </el-tag>
        </div>

      </div>
      <div class="transfer-container transfer-diy-empty">
        <treeTransfer
          ref="transfer"
          :to_data="transferData"
          :from_data="fieldListArr"
          :button_text="['加入右侧','加入左侧']"
          :title="['数据表字段','目标导入字段']"
          @removeBtn="fieldChange"
          @addBtn="fieldChange"
        />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button class="ok" type="primary" @click="handelOk">提交</el-button>
        <el-button class="cancel" @click="dialogVisible = false">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import ImportBtn from '../importField';
import treeTransfer from 'el-tree-transfer';
// import { saveTempReport } from '@/api/reportManage';

export default {
  components: { ImportBtn, treeTransfer },
  props: {
    radioList: {
      type: Object,
      default: () => {
        return {};
      }
    },
    importApi: {
      type: String,
      default: '/admin/report/importTempReport'
    },
    isNeedBaseFiled: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      formRules: {
        categoryId: [{ required: true, trigger: 'change', message: '请选择字段分类' }]
      },
      dialogVisible: false,
      loading: false,
      transferData: [],
      fileName: [],
      fieldListArr: [],
      rightData: [],
      tempFieldListArr: []
    };
  },
  methods: {
    onSucess(dataRes) {
      // 插入数据
      const data = dataRes;
      data.forEach(i => {
        const repeatData = this.handelDataRepeat(i.fieldList);
        const children = repeatData.map((field, fieldIndex) => {
          return {
            isLast: true,
            label: field.fieldName,
            fieldData: field.fieldData
          };
        });
        i.pid = 0;
        i.label = i.name;
        i.children = children;

        this.tempFieldListArr.push(JSON.parse(JSON.stringify(i)));
        // 动态添加 id 和 pid  tempFieldListArr
        this.handleDataId(i, JSON.parse(JSON.stringify(this.tempFieldListArr)));
        this.fieldListArr.push(i);
      });
    },
    // 去重
    handelDataRepeat(data) {
      const fieldList = [];
      this.fieldListArr.forEach(i => {
        i.children.forEach(j => {
          fieldList.push(j.label);
        });
      });
      data = data.filter(j => {
        return !fieldList.includes(j.fieldName);
      });
      return data;
    },
    // 动态添加树形结构的id
    handleDataId(data, temp = null) {
      let tempFieldListArr = this.tempFieldListArr;
      if (!temp) {
        tempFieldListArr = temp;
      }
      const id = tempFieldListArr.length;
      data.id = id + '';
      data.children.forEach((i, index) => {
        const cid = index + 1 + '';
        i.id = id + '-' + cid;
        i.pid = id + '';
      });
      this.fileName.push(data);
      this.tempFieldListArr.forEach((i, index) => {
        i.id = index + 1 + '';
      });
    },
    fieldChange(leftData, rightData, item) {
      this.fieldListArr = leftData;
      this.rightData = rightData;
      this.transferData = rightData;
    },
    deleteTable(item) {
      this.fileName = this.fileName.filter(i => {
        return i.id !== item.id;
      });
      this.fieldListArr = this.fieldListArr.filter(i => {
        return i.id !== item.id;
      });
      this.rightData = this.rightData.filter(i => {
        return i.id !== item.id;
      });
      this.transferData = this.transferData.filter(i => {
        return i.id !== item.id;
      });
      this.$refs['transfer'].clearChecked();
    },
    async handelOk() {
      const rightData = JSON.parse(JSON.stringify(this.rightData));
      if (rightData && rightData.length) {
        const params = {
          fieldNameList: []
        };
        rightData.forEach(i => {
          if (!i.isLast) {
            i.children.forEach(j => {
              if (j.isLast) {
                params.fieldNameList.push({
                  name: j.label,
                  sourceData: j.fieldData || null
                });
              }
            });
          }
        });
        params.fieldNameList = this.removeRepeat(params.fieldNameList);
        this.$emit('onSuccess', params.fieldNameList);
        this.dialogVisible = false;
      } else {
        this.$message({
          type: 'warning',
          message: '请选择字段'
        });
      }
    },
    removeRepeat(data) {
      const hash = {};
      if (this.radioList.name) {
        hash[this.radioList.name] = 1;
      }
      const newArr = data.reduce((item, next) => {
        if (!hash[next.name]) {
          hash[next.name] = item.push(next);
        }
        return item;
      }, []);
      return newArr;
    },
    handleClose() {

    }
  }
};
</script>
<style lang="scss" scoped>
.file-list {
  display: flex;
  // align-items: center;
  flex-wrap: wrap;
  .tag {
    margin-right: 10px;
    margin-bottom: 10px;
    display: flex;
    align-items: center;
    & ::v-deep {
      .el-icon-close {
        height: auto !important;
        position: relative;
        top: 2px;
      }
    }
  }
  .import-btn-container {
    display: flex;
  }
  .table-name-container {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    width: 84%;
  }
  .text-overflow {
    display: inline-block;
    max-width: 141px;
    overflow: hidden;
    text-overflow: ellipsis;
  }

}
.transfer {
  height: 348px !important;
  width: 568px !important;
}
.dialog-footer {
  display: flex;
  justify-content: center;
  .ok {
    width: 120px;
    font-size: 14px;
  }
  .cancel {
    width: 80px;
    font-size: 14px;
    color: #406EFF;
    background:rgba(239,243,251,1);
    border: none;
  }
}
</style>
